﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.interfaces;
using umbraco.presentation.cache;
using umbraco.uicontrols;
using umbraco.IO;
using umbraco.controls;
using umbraco.editorControls;
using Commerce.Common;

namespace CommerceForUmbraco.adminSection.commerce
{
    public partial class editProductOptionItem : umbraco.BasePages.UmbracoEnsuredPage
    {
        public TabPage MainTab;

        AttributeItem thisOptionItem;

        protected void Page_Load(object sender, EventArgs e)
        {
            string itemId = Request.QueryString.Get("id");
            thisOptionItem = new AttributeItem(int.Parse(itemId));

            if (!IsPostBack)
            {
                LiteralItemID.Text = thisOptionItem.AttributeItemId.ToString();
                TextBoxName.Text = thisOptionItem.Name;
                TextBoxAdjustment.Text = thisOptionItem.Adjustment.ToString();
                TextBoxSortOrder.Text = thisOptionItem.SortOrder.ToString();
                TextBoxSku.Text = thisOptionItem.SkuSuffix;
            }

            this.Pane1.Text = "Edit Product Option Item";
            this.pp_itemId.Text = "Option Item ID";
            this.pp_name.Text = "Option Item Name";
            this.pp_adjustment.Text = "Price Adjustment";
            this.pp_order.Text = "Sort Order";
            this.pp_skuSuffix.Text = "SKU Suffix";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private umbraco.uicontrols.TabView GetDashboardPanel()
        {
            umbraco.uicontrols.TabView tabview =
                (umbraco.uicontrols.TabView)FindControlRecursive(this.Page.Master, "tabControl");
            return tabview;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Root"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static Control FindControlRecursive(Control Root, string Id)
        {
            if (Root.ID == Id)
                return Root;

            foreach (Control Ctl in Root.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, Id);
                if (FoundCtl != null)
                    return FoundCtl;
            }

            return null;
        }

        private void save_click(object sender, ImageClickEventArgs e)
        {
            if (this.SaveProduct(this.TextBoxName.Text, base.Request.QueryString["id"]))
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "Product Option Item saved"), "");
            }
            else
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "commerceItemErrorHeader"), ui.Text("speechBubbles", "commerceItemErrorText"));
            }
        }

        private bool SaveProduct(string itemName, string optionItemId)
        {
            int itemId = -1;
            AttributeItem productOptionItem;
            
            if (Int32.TryParse(optionItemId, out itemId))
            {
                productOptionItem = new AttributeItem("AttributeItemId", itemId);
            }
            else
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0}", "Couldn't save product because productOptionID is invalid."));

                return false;
            }

            try
            {
                productOptionItem.Name = this.TextBoxName.Text;
                productOptionItem.Adjustment = Decimal.Parse(TextBoxAdjustment.Text);
                productOptionItem.SortOrder = Int32.Parse(TextBoxSortOrder.Text);
                productOptionItem.SkuSuffix = TextBoxSku.Text;

                productOptionItem.Save("We Love Runners");

                return true;
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));

                return false;
            }
        }

        #region load routines
        protected override void OnInit(EventArgs e)
        {

            // Tab setup
            MainTab = tabControl.NewTabPage("Product Option Items");
            MainTab.Controls.Add(Pane1);

            // Main Tab
            ImageButton save = MainTab.Menu.NewImageButton();
            save.Click += new ImageClickEventHandler(this.save_click);
            save.AlternateText = "Save";
            save.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            base.Load += new EventHandler(this.Page_Load);
            this.InitializeComponent();
            base.OnInit(e);
        }

        private umbraco.cms.businesslogic.web.DocumentType GetContentPageDocumentType()
        {
            return umbraco.cms.businesslogic.web.DocumentType.GetByAlias("ContentPage");
        }

        private void InitializeComponent()
        {
        }
        #endregion

    }
}